package com.ftdigital.primemovers_operators.fragment;


import android.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ftdigital.primemovers_operators.MainActivity;
import com.ftdigital.primemovers_operators.MyApplication;
import com.ftdigital.primemovers_operators.R;
import com.ftdigital.primemovers_operators.config.GlobalData;
import com.ftdigital.primemovers_operators.config.RequestAddr;
import com.ftdigital.primemovers_operators.model.AddOilInfo;
import com.ftdigital.primemovers_operators.model.BaseModel;
import com.ftdigital.primemovers_operators.model.Order;
import com.ftdigital.primemovers_operators.util.MethedUtil;
import com.ftdigital.primemovers_operators.util.http.AjaxCallBack;
import com.google.gson.JsonSyntaxException;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;
import org.apache.http.client.protocol.RequestProxyAuthentication;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;

/**
 * 加油详情
 */
@EFragment(R.layout.fragment_add_oil_detail)
public class AddOilDetailFragment extends BaseFragment {


    @ViewById(R.id.back_btn)
    ImageButton backBtn;

    @ViewById(R.id.toptitle_title)
    TextView topTitle;

    @FragmentArg("addOilInfo")
    AddOilInfo addOilInfo;

    @ViewById(R.id.add_oil_detail_oiltype)
    TextView oilType;

    @ViewById(R.id.add_oil_detail_marketprice)
    TextView marketPrice;

    @ViewById(R.id.privateCenter_contactprice)
    TextView contactPrice;

    @ViewById(R.id.total_price)
    TextView totalPrice;
    @ViewById(R.id.add_oil_num)
    EditText addOilAmount;
    @ViewById(R.id.dailyDiscount)
    TextView dailyDiscount;

    @ViewById(R.id.detail_content)
    EditText detailContent;

    AddOilDetailFragment addOilDetailFragment;

    private boolean isModefy = false; // false :新建状态  true:修改状态

    @AfterViews
    @Override
    void initView() {
        addOilDetailFragment = this;
        backBtn.setVisibility(View.VISIBLE);
        topTitle.setText(getResources().getString(R.string.title_addios_detail));

        loadData();

        addOilAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().trim().equals("")) {
                    totalPrice.setText("0");
                    return;
                }

                if (!charSequence.toString().trim().equals("") && !charSequence.toString().trim().equals(".")) {
                    if (charSequence.toString().indexOf(".") != -1) {
                        if (charSequence.toString().length() > charSequence.toString().indexOf(".") + 3) {
                            return;
                        }
                    }
                    Double totalAmount = Double.valueOf(charSequence.toString());
                    DecimalFormat decimalFormat = new DecimalFormat(".00");
                    totalPrice.setText(
                            decimalFormat.format(
                                    totalAmount * addOilInfo.getData().getList().get(0).getPrice()
                            )
                    );
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void loadData() {
        oilType.setText(addOilInfo.getData().getList().get(0).getGas_type());
        contactPrice.setText(addOilInfo.getData().getList().get(0).getPrice() + "");
        marketPrice.setText(addOilInfo.getData().getList().get(0).getLocalprice() + "");
        dailyDiscount.setText(addOilInfo.getData().getList().get(0).getDiscount());
    }

    @Click({R.id.back_btn, R.id.submit})
    @Override
    void Click(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                MainActivity.getInstance().getSupportFragmentManager().popBackStack();
                break;
            case R.id.submit:
                if (!checkValidate()) {
                    return;
                }
                if (MethedUtil.isCheckedSpeChar(getActivity(), addOilAmount.getText().toString())) {
                    return;
                }
                addOilInfo.getData().getList().get(0).setAmountNum(addOilAmount.getText().toString().trim());
                addOilInfo.getData().getList().get(0).setTotalPrice(totalPrice.getText().toString().trim());
                if (isModefy) {
                    modifyOrder();
                } else {
                    checkBalance();
//                    submitOrder();
                }
                break;
        }
    }

    //新建订单
    private void checkBalance() {
        requestParams = "car_id=" + addOilInfo.getData().getCar_id()
                + "&supplier_id=" + MyApplication.userInfo.getData().getSupplier_id()
                + "&total_price=" + addOilInfo.getData().getList().get(0).getTotalPrice();

        requestUrl = RequestAddr.checkBlace + requestParams;
        xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object object) {
                super.onSuccess(object);
                dealCheckData(object);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    private void dealCheckData(Object object) {
        try {
            baseModel = gson.fromJson(object.toString(), BaseModel.class);
        } catch (JsonSyntaxException e) {
            return;
        }
        if (baseModel.isFlag()) {
            submitOrder();
        }else {
            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    //新建订单
    private void submitOrder() {
//        Log.i(GlobalData.TAG, "submitOrder type:" + addOilInfo.getData().getList().get(0).getGas_type().replace("#", ""));
        Log.i(GlobalData.TAG, "note:" + detailContent.getText());
        try {
            requestParams = "car_id=" + addOilInfo.getData().getCar_id()
                    + "&convention_price=" + addOilInfo.getData().getList().get(0).getPrice()
                    + "&gas_type=" + URLEncoder.encode(addOilInfo.getData().getList().get(0).getGas_type().replace("#", ""), "utf-8")
                    + "&gasstation_id=" + MyApplication.userInfo.getData().getGasstation_id()
                    + "&price=" + addOilInfo.getData().getList().get(0).getLocalprice()
                    + "&qty=" + addOilInfo.getData().getList().get(0).getAmountNum()
                    + "&supplier_id=" + MyApplication.userInfo.getData().getSupplier_id()
                    + "&total_price=" + addOilInfo.getData().getList().get(0).getTotalPrice()
                    + "&user_id=" + MyApplication.userInfo.getData().getUser_id()
                    + "&note=" + detailContent.getText().toString().trim().replace(" ", "").replace("\n", "").replace("\r", "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        requestUrl = RequestAddr.creatOrder + requestParams;
        xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object object) {
                super.onSuccess(object);
                dealData(object);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    //修改订单
    private void modifyOrder() {
//        Log.i(GlobalData.TAG, "modifyOrder type:" + addOilInfo.getData().getList().get(0).getGas_type().replace("#", ""));
        try {
            requestParams = "car_id=" + addOilInfo.getData().getCar_id()
                    + "&convention_price=" + addOilInfo.getData().getList().get(0).getPrice()
                    + "&gas_type=" + URLEncoder.encode(addOilInfo.getData().getList().get(0).getGas_type().replace("#", ""), "utf-8")
                    + "&gasstation_id=" + MyApplication.userInfo.getData().getGasstation_id()
                    + "&price=" + addOilInfo.getData().getList().get(0).getLocalprice()
                    + "&qty=" + addOilInfo.getData().getList().get(0).getAmountNum()
                    + "&supplier_id=" + MyApplication.userInfo.getData().getSupplier_id()
                    + "&total_price=" + addOilInfo.getData().getList().get(0).getTotalPrice()
                    + "&user_id=" + MyApplication.userInfo.getData().getUser_id()
                    + "&order_no=" + order.getData().getOrder_no()
                    + "&note=" + detailContent.getText().toString().trim().replace(" ", "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        requestUrl = RequestAddr.modifyOrder + requestParams;
        xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object object) {
                super.onSuccess(object);
                dealData(object);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    Order order;

    private void dealData(Object object) {
        try {
            order = gson.fromJson(object.toString(), Order.class);
        } catch (JsonSyntaxException e) {
            baseModel = gson.fromJson(object.toString(), BaseModel.class);
            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
            return;
        }
        isModefy = true;
        showSelect();
    }

    private boolean checkValidate() {
        if (addOilAmount.getText().toString().trim().equals("")) {
            Toast.makeText(getActivity(), "请输入加油数量", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (MethedUtil.isCheckedSpeChar(getActivity(), detailContent.getText().toString().trim())
                ||MethedUtil.isCheckedSpeChar(getActivity(), detailContent.getText().toString().trim())) {
            return false;
        }
        return true;
    }

    AlertDialog alertDialog;

    private void showSelect() {
        alertDialog = new AlertDialog.Builder(MainActivity.getInstance()).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.noticy_dialog);
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        TextView backBtn = (TextView) window.findViewById(R.id.backbtn);
        TextView sureInfo = (TextView) window.findViewById(R.id.sureinfo);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
//                MainActivity.getInstance().getSupportFragmentManager().popBackStack();
            }
        });
        sureInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                MainActivity.getInstance().switchFragment(addOilDetailFragment, EnSureFragment_.builder()
                        .order_no(order.getData().getOrder_no())
                        .build());
            }
        });
    }
}
